﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using Katilgan.ORM;
using System.Data.SqlClient;
using System.Data.Common;
using System.Configuration;

namespace WebUI.DataLayer.Library
{
    [DataObject]
    public abstract class BaseService<T> where T : class,new()
    {
        private string _connectionString;
        public virtual string ConnectionString
        {
            get
            {
                if (string.IsNullOrEmpty(_connectionString))
                {
                    _connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
                }
                return _connectionString;
            }
        }
        private string _providerName;
        public virtual string ProviderName
        {
            get
            {
                if (string.IsNullOrEmpty(_providerName))
                {
                    _providerName = ConfigurationManager.ConnectionStrings["DefaultConnection"].ProviderName;
                }
                return _providerName;
            }
        }

        private DataContext<T> _dbContext = null;
        protected DataContext<T> dbContext
        {
            get
            {
                if (_dbContext == null)
                {
                    _dbContext = new DataContext<T>() { ConnectionString = this.ConnectionString, ProviderName = this.ProviderName };
                }
                return _dbContext;
            }
        }
        [DataObjectMethod(DataObjectMethodType.Select)]
        public virtual List<T> SelectAll()
        {
            return dbContext.GetAllData();
        }

        [DataObjectMethod(DataObjectMethodType.Select)]
        public virtual List<T> SelectAll(string orderbyColumn)
        {
            return dbContext.GetAllData(orderbyColumn);
        }

        [DataObjectMethod(DataObjectMethodType.Select)]
        public virtual List<T> SelectByExample(T example)
        {
            return dbContext.GetByExample(example);
        }

        [DataObjectMethod(DataObjectMethodType.Insert)]
        public virtual bool Insert(T entity)
        {
            return dbContext.InsertEntity(entity);
        }

        [DataObjectMethod(DataObjectMethodType.Update)]
        public virtual bool Update(T entity)
        {
            return dbContext.UpdateEntity(entity);
        }

        public TE RunCommand<TE>(Func<DbCommand, TE> dbExecute, string conStr)
        {
            return dbContext.RunCommand<TE>(dbExecute, conStr);
        }

        protected TE RunCommand<TE>(Func<DbCommand, TE> dbExecute)
        {
            return dbContext.RunCommand<TE>(dbExecute, this.ConnectionString);
        }
    }
}